<template>
  <div class="login">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="auto"
      class="login-ruleForm"
    >
      <el-form-item>
        <h1>登录</h1>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" type="password" show-password autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm()" style="width: 100%"> 登录 </el-button>
      </el-form-item>
      <el-form-item>
        <RouterLink to="/register">去注册</RouterLink>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { loginApi, getAvatarApi } from '@/api/api'
import { useRouter } from 'vue-router' // 导入 useRouter 钩子函数
import { useUserStore } from '@/stores/user'

const router = useRouter() // 调用 useRouter 钩子函数

const ruleFormRef = ref()

const ruleForm = reactive({
  username: '',
  password: '',
})

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur' },
  ],
})

const userStore = useUserStore()

const submitForm = async () => {
  const response = await loginApi(ruleForm.username, ruleForm.password)
  const avatar = await getAvatarApi(ruleForm.username) // 获取用户头像
  console.log(response)
  console.log(avatar) // 打印头像数据，用于调试
  if (response.data.code === 200) {
    const token = response.data.data

    localStorage.setItem('token', token)
    const user = {
      username: ruleForm.username,
      avatar: avatar.data.data, // 将头像数据存储到用户对象中
    }
    localStorage.setItem('userInfo', JSON.stringify(user))
    userStore.user = user
    ElMessage.success('登录成功')
    router.push('/') // 注册成功后跳转到登录页面
  } else {
    ElMessage.error('注册失败')
  }
}
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;
  background-color: rgb(210, 210, 210);

  display: flex;
  align-items: center;
  justify-content: center;

  .login-ruleForm {
    width: 300px;
    padding: 20px;
    border-radius: 10px;
    background-color: white;
  }
}
</style>
